package com.xjtu.duansheli.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.duansheli.exception.MyException;
import com.xjtu.duansheli.entity.UserInfo;
import com.xjtu.duansheli.mapper.UserInfoMapper;
import com.xjtu.duansheli.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 漩涡鸣人
 * @since 2020-10-24
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public List<UserInfo> getAllUser(int current, int size) {
        Page<UserInfo> page = new Page<>(current,size);
        userInfoMapper.selectPage(page, null);
        System.out.println(page.getTotal());
        return page.getRecords();
//        List<UserInfo> userInfos = userInfoMapper.selectList(null);
//        if(userInfos.size() == 0){
//            throw new MyException(500,"数据库中无数据！");
//        }return userInfos;
    }

    @Override
    public UserInfo getUserByid(Long uid) {
        UserInfo userInfo = userInfoMapper.selectById(uid);
        if(userInfo == null){
            throw new MyException(500,"不存在该用户！");
        }
        return userInfo;
    }

    @Override
    public int addUser(UserInfo user) {
        try{
            return userInfoMapper.insert(user);
        }catch (Exception e){
            throw new MyException(500,"添加用户失败！");
        }
    }

    @Override
    public int updateUser(UserInfo user) {
        try{
            return userInfoMapper.updateById(user);
        }catch (Exception e){
            throw new MyException(500,"更新用户失败！");
        }
    }

    @Override
    public int deleteUser(Long uid) {
        try{
            return userInfoMapper.deleteById(uid);
        }catch (Exception e){
            throw new MyException(500,"删除用户失败！");
        }
    }

    @Override
    public UserInfo getUserByPhone(String phone) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);

        List<UserInfo> userInfos = userInfoMapper.selectByMap(map);
        if(userInfos.size() == 0){
            throw new MyException(400,"该手机号还未注册账户，请先注册账户和认证！");
        }
        return userInfos.get(0);
    }

    @Override
    public int getTotal() {
        return userInfoMapper.selectCount(null);
    }
}
